package com.example.data.factory.web1.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api")
public class JsonImportController {
    /**
     * 独立的JSON导入接口。
     *
     * @param jsonData 包含接口信息的JSON数据
     * @return 处理结果
     */
    @PostMapping("/importJsonData")
    public ResponseEntity<Map<String, Object>> importJsonData(@RequestBody Map<String, Object> jsonData) {
        try {
            // 创建一个Map来存储转换后的字符串
            Map<String, String> resultData = new HashMap<> ();
            if (jsonData.containsKey ( "inputParamBody" )) {
                resultData.put ( "inputParamBody", convertToJsonString ( jsonData.get ( "inputParamBody" ) ) );
            }
            if (jsonData.containsKey ( "outputParam" )) {
                resultData.put ( "outputParam", convertToJsonString ( jsonData.get ( "outputParam" ) ) );
            }

            // 构建响应
            Map<String, Object> response = new HashMap<> ();
            response.put ( "code", 100200 );
            response.put ( "msg", "返回成功" );
            response.put ( "data", resultData );

            return new ResponseEntity<> ( response, HttpStatus.OK );
        } catch (Exception e) {
            Map<String, Object> errorResponse = new HashMap<> ();
            errorResponse.put ( "code", 100500 );
            errorResponse.put ( "msg", "系统内部错误: " + e.getMessage () );
            return new ResponseEntity<> ( errorResponse, HttpStatus.INTERNAL_SERVER_ERROR );
        }
    }

    /**
     * 将对象转换为JSON字符串，并确保所有双引号都被转义。
     *
     * @param obj 需要转换的对象
     * @return 转换后的JSON字符串
     * @throws JsonProcessingException 如果转换过程中出现错误
     */
    private String convertToJsonString(Object obj) throws JsonProcessingException {
        if (obj == null) {
            return null;
        }
        ObjectMapper objectMapper = new ObjectMapper ();
        return objectMapper.writeValueAsString ( obj )
                .replace ( "\"", "\"" )  // 替换所有的"为\"
                .replaceAll ( "\r|\n", "" ); // 移除可能存在的换行符
    }
}

